package com.woniu.market_stall.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.market_stall.entity.Manager;
import com.woniu.market_stall.mapper.ManagerMapper;
import com.woniu.market_stall.vo.ManagerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
public class ManagerService {

    @Autowired
    ManagerMapper managerMapper;

    public Manager login(String name){
        return managerMapper.selectByName(name);
    }

    public int modifyByMid(Manager manager) {
        return managerMapper.updateByPrimaryKey(manager);
    }
    public PageInfo<ManagerVo> queryByPage(Integer now, Integer size, String name) {
        PageHelper.startPage(now,size);
        List<ManagerVo> list = managerMapper.selectManagerByName(name);
        return new PageInfo<>(list);
    }

    @Transactional
    public void add(ManagerVo managerVo) {
        //1. 添加管理员
        managerMapper.insertManager(managerVo); //插入之后 返回当前管理员的 ID
        //2. 授予角色
        managerMapper.insertRoleToManager(managerVo.getId(),managerVo.getRoleIds());
    }

    @Transactional
    public void modify(ManagerVo managerVo) {
        //0.先删除当前管理员拥有的所有角色
        managerMapper.update(managerVo);
        //1. 添加管理员的角色
        managerMapper.deleteRoleByMid(managerVo.getId());
        //2. 修改管理员
        List<Integer> list = new ArrayList<>();
        for (Integer s : managerVo.getRoleIds()){
            list.add(s);
        }
        managerMapper.insertRoleByMid(managerVo.getId(),list);
    }

    @Transactional
    public void removeByKey(Integer id) {
        //0.先删除当前管理员拥有的所有角色
        managerMapper.deleteManagerAndRoleByMid(id);
        //1. 删除管理员
        managerMapper.deleteBPK(id);
    }

    public List<String> getRoleNamesByMid(int mid) {
        return managerMapper.selectRoleNamesByMid(mid);
    }

    public Integer findDeptId(String deptName) {
       return managerMapper.queryDeptId(deptName);
    }

    public List<ManagerVo> queryAllManager() {
        return managerMapper.selectAllManager();
    }
}
